package com.newworld.dmsapp2.register;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.LoginActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.HouseManageListActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class UserMessageActivity extends BaseActivity implements
		OnClickListener, OnFocusChangeListener {
	private Button btn_user_next;
	private LinearLayout leftlayout;
	private EditText userNameEdtTxt;
	private EditText pwdEdtTxt;
	private EditText pwdAgainEdtTxt;
	public static int INTENT_FLAG = 0;
	public static int INTENT_USER_FLAG = 0;
	private String usernameFlag = "failure";
	private ProgressBar regiterProBar;
	private Intent intent;
	private String houseID;
	protected String ownerphone;
	protected String ownername;
	protected String postscript = "";
	protected String relationtypeid;
	private String invitecode = "0";
	private String relationhost = "402881f24feabdb5014feae3786e0003";
	private String sessionId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register_user_message);
		initData();
		initViews();
		initEvents();
	}

	private void initData(){
		User user = SingleSample.getInstance(this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
	}
	
	@Override
	protected void initViews() {
		TextView titleView = (TextView) findViewById(R.id.titlebar_left_center_title);
		titleView.setText(Config.TITLE_HOUSE_ATTATCH);
		leftlayout = (LinearLayout) findViewById(R.id.titlebar_left_left_layout);
		btn_user_next = (Button) findViewById(R.id.reg_user_btn);
		userNameEdtTxt = (EditText) findViewById(R.id.reg_user_name);
		pwdEdtTxt = (EditText) findViewById(R.id.reg_user_pwd);
		pwdAgainEdtTxt = (EditText) findViewById(R.id.reg_user_pwd_again);
		regiterProBar = (ProgressBar) findViewById(R.id.proBar_register);
		intent = getIntent();
		if (intent != null) {
			houseID = intent.getStringExtra("houseID");
			ownername = intent.getStringExtra("ownername");
			ownerphone = intent.getStringExtra("ownerphone");
			postscript = intent.getStringExtra("postscript");
			relationtypeid = intent.getStringExtra("relationtypeid");
			invitecode = intent.getStringExtra("invitecode");
			System.out.print("ownername------->" + ownername);
			System.out.print("ownerphone------->" + ownerphone);
			System.out.print("relationtypeid-------11>" + relationtypeid);
			System.out.print("invitecode-------44>" + invitecode);
		}

	}

	@Override
	protected void initEvents() {
		btn_user_next.setOnClickListener(this);
		leftlayout.setOnClickListener(this);
		userNameEdtTxt.setOnFocusChangeListener(this);
		pwdEdtTxt.setOnFocusChangeListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.reg_user_btn:
			if (INTENT_FLAG == 0) {
				if (!(pwdAgainEdtTxt.getText() + "").trim().equals(
						(pwdEdtTxt.getText() + "").trim())) {
					Toast.makeText(UserMessageActivity.this, "两次密码输入不一致！",
							Toast.LENGTH_SHORT).show();
				} else {
					System.out.print("relationtypeid-------2222>"
							+ relationtypeid);
					if (relationtypeid.equals(relationhost)) {
						
						System.out.println("户主注册流程！");
						hostRegister();

					} else if (!relationtypeid.equals(relationhost)
							&& !relationtypeid.equals("")) {

						System.out.println("非户主注册流程！");
						disHostRegister();

					} else {

						System.out.println("邀请码注册流程！");
						inviteCodeRegister();

					}

				}

			} else if (INTENT_FLAG == 1) {
				intentActivity(UserMessageActivity.this,
						HouseManageListActivity.class);
			}

			break;
		case R.id.titlebar_left_left_layout:
			if (INTENT_USER_FLAG == 0) {
				
				finish();
				
			} else if (INTENT_USER_FLAG == 1) {
				// 为避免客户想改写错数据，点击返回到前一个界面，导致未传数据。
				Intent intent = new Intent(UserMessageActivity.this,
						RegisterDishostActivity.class);
				intent.putExtra("houseID", houseID);
				System.out.println("houseID" + houseID);
				intent.putExtra("ownername", ownername);
				intent.putExtra("ownerphone", ownerphone);
				intent.putExtra("relationtypeid", relationtypeid);
				startActivity(intent);
			} else if (INTENT_USER_FLAG == 2) {
				Intent intent = new Intent(UserMessageActivity.this,
						InvitecodeRegistActivity.class);
				intent.putExtra("houseID", houseID);
				System.out.println("houseID" + houseID);
				intent.putExtra("ownername", ownername);
				intent.putExtra("ownerphone", ownerphone);
				intent.putExtra("relationtypeid", relationtypeid);
				startActivity(intent);
			}
			break;
		default:
			break;
		}
	}

	private void inviteCodeRegister() {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String reason = "";
			private String flag;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
					regiterProBar.setVisibility(android.view.View.VISIBLE);
				} else {
					Toast.makeText(UserMessageActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
					try {
						Map<String, String> map = new HashMap<String, String>();
						// map.put("language", "");
						// 用户名
						map.put("registerUserName",
								(userNameEdtTxt.getText() + "").trim());
						// 用户密码
						map.put("registerPassword",
								(pwdEdtTxt.getText() + "").trim());
						// 房屋id
						map.put("houseId", houseID);
						// 邀请码
						map.put("inviteCode", invitecode);

						System.out.print("注册名registerUserName--->"
								+ userNameEdtTxt.getText() + "");
						System.out.print("注册密码registerPassword--->"
								+ pwdEdtTxt.getText() + "");
						System.out.print("注册邀请码invitecode--->" + invitecode);
						
						String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL,Config.REGISTER_URL), map,sessionId);
						System.out.println("result" + result);
						reason = new JSONObject(result).getString("message");
						flag = new JSONObject(result).getString("flag");
						System.out.println("reason--->" + reason);
						System.out.println("flag--->" + flag);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				// regiterProBar.setVisibility(View.INVISIBLE);
				if (flag.equals("success")) {
					reason = "邀请码注册成功！";
					Toast.makeText(UserMessageActivity.this, reason,
							Toast.LENGTH_SHORT).show();
					intentActivity(UserMessageActivity.this,
							LoginActivity.class);
				} else {
					new AlertDialog.Builder(UserMessageActivity.this)
							.setTitle("提示").setMessage(reason)
							.setNegativeButton("取消", null).create().show();

				}

			}
		}.execute(null, null, null);
	}

	private void disHostRegister() {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String reason = "";
			private String flag;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
					regiterProBar.setVisibility(android.view.View.VISIBLE);
				} else {
					Toast.makeText(UserMessageActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
					try {
						Map<String, String> map = new HashMap<String, String>();
						map.put("language", "");
						// 用户名
						map.put("registerUserName",
								(userNameEdtTxt.getText() + "").trim());
						// 用户密码
						map.put("registerPassword",
								(pwdEdtTxt.getText() + "").trim());
						// 房屋id
						map.put("houseId", houseID);
						// 户主姓名
						map.put("ownerName", ownername);
						// 户主电话
						map.put("ownerPhone", ownerphone);
						// 业主类型（户主。非户主）
						map.put("relationTypeId", relationtypeid);
						map.put("postscript", postscript);
						// 邀请码
						// map.put("invitecode", "");
						String setsessionid = "";
						User user = SingleSample.getInstance(UserMessageActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL,Config.REGISTER_URL), map,sessionId);
						/*String result = HttpUtil.postRequest(
								Config.REGISTER_URL, map);*/
						System.out.println("ownername的值是：" + ownername);
						System.out.println("result" + result);
						reason = new JSONObject(result).getString("message");
						flag = new JSONObject(result).getString("flag");
						System.out.println("flag---->" + flag);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				regiterProBar.setVisibility(View.INVISIBLE);
				// 这里曾经多次报错，success写成了success!~!!~!
				if (flag.equals("success")) {
					reason = "非户主注册成功！";
					Toast.makeText(UserMessageActivity.this, reason,
							Toast.LENGTH_SHORT).show();
					intentActivity(UserMessageActivity.this,
							LoginActivity.class);
				} else {
					new AlertDialog.Builder(UserMessageActivity.this)
							.setTitle("提示").setMessage(reason)
							.setNegativeButton("取消", null).create().show();

				}

			}
		}.execute(null, null, null);
	}

	// 户主注册请求
	private void hostRegister() {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String reason = "";
			private String flag;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
					regiterProBar.setVisibility(android.view.View.VISIBLE);
				} else {
					Toast.makeText(UserMessageActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
					try {
						Map<String, String> map = new HashMap<String, String>();
						// map.put("language", "");
						// 用户名
						map.put("registerUserName",
								(userNameEdtTxt.getText() + "").trim());
						// 用户密码
						map.put("registerPassword",
								(pwdEdtTxt.getText() + "").trim());
						// 房屋id
						map.put("houseId", houseID);
						// 户主姓名
						map.put("ownerName", ownername);
						// 户主电话
						map.put("ownerPhone", ownerphone);
						// 邀请码
						map.put("inviteCode", invitecode);
						// 附言
						map.put("postscript", postscript);
						// 业主类型（户主。非户主）
						// 这里户主这样写死了，非户主还要改》》》
						map.put("relationTypeId", relationhost);
						// map.put("postscript", "");
						// 邀请码
						// map.put("invitecode", "");
						System.out.println("registerusername"
								+ (userNameEdtTxt.getText() + "").trim()
								+ "-->" + "registerpassword"
								+ (pwdEdtTxt.getText() + "").trim()
								+ "-->houseid" + houseID + "-->ownername"
								+ ownername + "-->owerphone" + ownerphone
								+ "-->relationtypeid" + relationtypeid);
						String setsessionid = "";
						User user = SingleSample.getInstance(UserMessageActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL,Config.REGISTER_URL), map,sessionId);
						/*String result = HttpUtil.postRequest(
								Config.REGISTER_URL, map);*/
						System.out.println("result" + result);
						reason = new JSONObject(result).getString("message");
						// System.out.println("reason---->"+reason);
						flag = new JSONObject(result).getString("flag");
						System.out.println("flag---->" + flag);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				regiterProBar.setVisibility(View.INVISIBLE);
				if (flag.equals("success")) {
					reason = "户主注册成功！";
					Toast.makeText(UserMessageActivity.this, reason,
							Toast.LENGTH_SHORT).show();
					intentActivity(UserMessageActivity.this,
							LoginActivity.class);
				} else {
					// reason = new JSONObject(result).getString("message");
					if(reason.equals("房屋户主已经关联")){
						reason="该房屋户主已经注册";
					new AlertDialog.Builder(UserMessageActivity.this)
							.setTitle("提示").setMessage(reason)
							.setNegativeButton("取消", null).create().show();}

				else{
					new AlertDialog.Builder(UserMessageActivity.this)
					.setTitle("提示").setMessage(reason)
					.setNegativeButton("取消", null).create().show();
				}
					}

			}
		}.execute(null, null, null);
	}

	// 返回键的处理
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			if (INTENT_USER_FLAG == 0) {
				/*
				 * 为避免客户想改写数据或担心之前是否填写有误，点击返回到前一个界面，导致未 传数据houseId
				 */
				// Intent intent = new Intent(UserMessageActivity.this,
				// RegisterHostActivity.class);
				// intent.putExtra("houseID", houseID);
				// System.out.println("houseID" + houseID);
				//
				// startActivity(intent);
				finish();

				/*
				 * intentActivity(UserMessageActivity.this,
				 * RegisterHostActivity.class);
				 */
			} else if (INTENT_USER_FLAG == 1) {
				intentActivity(UserMessageActivity.this,
						RegisterDishostActivity.class);
			} else if (INTENT_USER_FLAG == 2) {
				intentActivity(UserMessageActivity.this,
						InvitecodeRegistActivity.class);
			}
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// EditText的监听事件
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.reg_user_name:
			if (!hasFocus) {
				confirmUsername();
			}

			break;
		case R.id.reg_user_pwd:
			if (!hasFocus) {
				confirmPwd();
			}
			break;
		}
	}

	private void confirmPwd() {
		// TODO Auto-generated method stub
		if ((pwdEdtTxt.getText() + "").trim().equals("")) {
			Toast.makeText(UserMessageActivity.this, "密码不能为空",
					Toast.LENGTH_SHORT).show();
		} else if (!Tool.isPwdNO(pwdEdtTxt.getText() + "")) {
			Toast.makeText(UserMessageActivity.this, "密码格式错误",
					Toast.LENGTH_SHORT).show();
		}
	}

	// 检查用户名是否已经存在
	private void confirmUsername() {
		// TODO Auto-generated method stub
		if ((userNameEdtTxt.getText() + "").trim().equals("")) {
			Toast.makeText(UserMessageActivity.this, "用户名不能为空",
					Toast.LENGTH_SHORT).show();
		} else if (!Tool.isUserNameNO(userNameEdtTxt.getText() + "")) {
			Toast.makeText(UserMessageActivity.this, "用户名格式错误",
					Toast.LENGTH_SHORT).show();
		} else {

			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					if (!Tool.isNetworkAvailable(UserMessageActivity.this)) {
						Toast.makeText(UserMessageActivity.this, "请检查网络连接！",
								Toast.LENGTH_SHORT).show();
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if (Tool.isNetworkAvailable(UserMessageActivity.this)) {
						try {
							Map<String, String> map = new HashMap<String, String>();
							map.put("username",
									(userNameEdtTxt.getText() + "").trim());
							
							String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL, Config.GETUSERNAME_URL),
									 map,sessionId);
							System.out.println("result" + result);
							if (new JSONObject(result).getString("flag")
									.equals("success")) {

								usernameFlag = new JSONObject(result)
										.getString("flag");
								System.out.println(usernameFlag);

							} else if (new JSONObject(result).getString("flag")
									.equals("failure")) {
								usernameFlag = new JSONObject(result)
										.getString("flag");
								System.out.println(usernameFlag);
							}

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					if (usernameFlag.equals("success")) {
						Toast.makeText(UserMessageActivity.this, "用户名可以使用！",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(UserMessageActivity.this, "用户名已被注册！",
								Toast.LENGTH_SHORT).show();
					}
				}
			}.execute(null, null, null);
		}
	}
}
